package typeinformation;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class BeanUtils {
	public static Object getProperty(Object instance, String field) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
		if (instance == null || field == null) {
			throw new IllegalArgumentException("params must not be null.");
		}
		Class<?> clazz = instance.getClass();
		Method[] ms = clazz.getDeclaredMethods();
		if (ms != null && ms.length > 0) {
			for (int i = 0, size = ms.length; i < size; i++) {
				Method m = ms[i];
				if (m.getName().equalsIgnoreCase("get" + field)) {
					return m.invoke(instance, (Object[]) null);
				}
			}
		}
		throw new UnsupportedOperationException("there is no method matches get" + field);
	}
	
	static class Student {
		private String name;
		public Student(String name) {
			this.name = name;
		}
		
		public String getName() {
			return name;
		}
	}
	
	public static void main(String... args) {
		Student stu = new Student("tonykwok");
		try {
			System.out.println(BeanUtils.getProperty(stu, "name").toString());
		} catch (IllegalArgumentException exc) {
			// TODO Auto-generated catch block
			exc.printStackTrace();
		} catch (IllegalAccessException exc) {
			// TODO Auto-generated catch block
			exc.printStackTrace();
		} catch (InvocationTargetException exc) {
			// TODO Auto-generated catch block
			exc.printStackTrace();
		}
	}

}
